﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Dcms.BLL;
using Dcms.Model;
using Dcms.Common;
using Dcms.UpdateModule;
public partial class Manage_Modle_Template_TempLateList : System.Web.UI.Page
{
    protected Dcms_TempLateBLL mydcmstemplatebll = new Dcms_TempLateBLL();
    protected CompetenceLib CL = new CompetenceLib();
    protected Dcms_TempLateModel mydcmstempmodel = new Dcms_TempLateModel();
    protected DcmsTempCreate mydcmstempcreate = new DcmsTempCreate();
    protected string TemplatePathStr = ConfigurationManager.AppSettings["TempLatePath"];
    protected string strPermissionID
    {
        get
        {
            return Request.QueryString["id"] + "";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            CL.IsLogin();

            if (!IsPostBack)
            {
                ReBinder();
            }
        }
        catch (Exception ex)
        {
            Log.LogHandler.LogError("Admin_UserManage_TempList.Page_Load", ex);
            throw ex;
        }
    }
    protected void ReBinder()
    {
        this.repAdmin.DataSource = GetAllTemplateList();
        this.repAdmin.DataBind();
    }
    protected DataTable GetAllTemplateList()
    {

        string tempSql = "";
        DcmsDataBaseHelper.ExecuteSql("delete from Dcms_TempLate", null);
        string templatePath = Utils.GetMapPath(TemplatePathStr);
        DirectoryInfo dirinfo = new DirectoryInfo(templatePath);
        foreach (DirectoryInfo dir in dirinfo.GetDirectories())
        {
            tempSql = "select Template_Name from Dcms_TempLate where Template_Name='" + dir.Name + "'";
            if (DcmsDataBaseHelper.GetOneFileValue(tempSql, "0") == "0")//表示不存在表中
            {
                mydcmstempmodel.Template_Author = "Dcms开发团队";
                mydcmstempmodel.Template_Copyright = "三五互联";
                mydcmstempmodel.Template_CreateTime = dir.CreationTime.ToString();
                mydcmstempmodel.Template_Directory = dir.FullName;
                mydcmstempmodel.Template_Fordntver = "NET Framework2.0以上";
                mydcmstempmodel.Template_Name = dir.Name;
                mydcmstempmodel.Template_State = 0;
                mydcmstempmodel.Template_UpdateTime = "从未生成过";
                mydcmstempmodel.Template_Ver = "Dcms 2.0";
                mydcmstemplatebll.AddModel(mydcmstempmodel);
            }
            else
            {
                DcmsDataBaseHelper.ExecuteSql("update Dcms_TempLate set Template_Directory='" + dir.FullName + "' where Template_Name='" + dir.Name + "'",null);
            }
        }
        DataTable dt =mydcmstemplatebll.GetModelList();
        return dt;
    }
    protected void repAdmin_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
    {
        int SucceedCount = 0, FailCount = 0,TemplateId=0;
        string AlertStrInfo = "";
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            if (e.CommandName == "Delecte")
            {
                
                    TemplateId = Convert.ToInt32(e.CommandArgument.ToString());
                    mydcmstemplatebll.DeleteModelByID(TemplateId);
                    Session.Add("Message", "删除功能模块成功，请返回！");
                    Session.Add("Url", "Modle/Template/TempList.aspx?id=" + strPermissionID);
                    Response.Redirect("../../Message.aspx", false);
               
            }
            if (e.CommandName == "Create" || e.CommandName == "CreateAll")
            {
                Label LabTempLateName = (Label)e.Item.FindControl("LabTempName");
                
                    FailCount = CreateTemplateByDirectory(e.CommandArgument.ToString(),e.CommandName, ref SucceedCount);
                    if (FailCount > 0)
                    {
                        DcmsDataBaseHelper.ExecuteSql("update Dcms_TempLate set Template_UpdateTime='" + DateTime.Now.ToString() + "',Template_State=0 where Template_Name='" + LabTempLateName.Text + "'", null);
                    }
                    else
                    {
                        DcmsDataBaseHelper.ExecuteSql("update Dcms_TempLate set Template_UpdateTime='" + DateTime.Now.ToString() + "',Template_State=1 where Template_Name='" + LabTempLateName.Text + "'", null);
                    }
                    AlertStrInfo = "成功生成" + SucceedCount + "个模板,失败" + FailCount + "个模板！！！";
                    Jscript.Alert(AlertStrInfo);
                
            }
            if (e.CommandName == "ChangeWebCode")
            {
                FailCount = ChangeFileCode(e.CommandArgument.ToString(), ref SucceedCount);
                AlertStrInfo = "成功生成" + SucceedCount + "个模板,失败" + FailCount + "个模板！！！";
                Jscript.Alert(AlertStrInfo);
            }
        }
    }
    private int CreateTemplateByDirectory(string Directorypath, string CreateType,ref int SucceedCount)
    {
        #region 生成模板
        int FailCount=0,ReturnFlag=0;
        TemplatePathStr = Server.MapPath(TemplatePathStr);
        DirectoryInfo myDirInfo = new DirectoryInfo(Directorypath);
        foreach (FileInfo TempFile in myDirInfo.GetFiles())
        {
            string extname = TempFile.Extension.ToLower();
            if (extname.Equals(".htm") || extname.Equals(".html") || extname.Equals(".asp") || extname.Equals(".aspx"))
            {
                string TempFolderName = Directorypath.Substring(TemplatePathStr.Length, Directorypath.Length - TemplatePathStr.Length);
                if (CreateType == "Create")
                {
                    if (Utils.GetDiffDate(TempFile.LastWriteTime, DateTime.Now, 3) < 4)
                    {

                        ReturnFlag = mydcmstempcreate.CreateTempLate(TempFile.Name, Directorypath +"/"+ TempFile.Name, TempFolderName);
                        if (ReturnFlag == 0)
                        {
                            SucceedCount++;
                        }
                        else
                        {
                            FailCount++;
                        }
                    }
                }
                else
                {
                    ReturnFlag = mydcmstempcreate.CreateTempLate(TempFile.Name, Directorypath + "/" + TempFile.Name, TempFolderName);
                    if (ReturnFlag == 0)
                    {
                        SucceedCount++;
                    }
                    else
                    {
                        FailCount++;
                    }
                }
            }
        }
        return FailCount;
        #endregion
    }
    protected int ChangeFileCode(string Directorypath, ref int SucceedCount)
    {
        int FailCount = 0;
        DirectoryInfo myDirInfo = new DirectoryInfo(Directorypath);
        foreach (FileInfo TempFile in myDirInfo.GetFiles())
        {
            string extname = TempFile.Extension.ToLower();
            if (extname.Equals(".htm") || extname.Equals(".html") || extname.Equals(".asp") || extname.Equals(".aspx") || extname.Equals(".ascx") || extname.Equals(".shtml"))
            {
                if (File.Exists(TempFile.FullName))
                {
                    try
                    {
                        string TempFileContent = DcmsFileManagerProcessor.ReadTextFile(TempFile.FullName);
                        DcmsFileManagerProcessor.SaveTextFile(TempFile.FullName, TempFileContent, "utf-8");
                        SucceedCount++;
                    }
                    catch(Exception ex)
                    {
                        FailCount++;
                    }

                }
            }
        }
        return FailCount;
    }
    public string ValidCreateState(string valid)
    {
        #region 生成状态图标
        if (valid == "1")
        {
            return "<img src=../../images/state2.gif />";
        }
        else
        {
            return "<img src=../../images/state3.gif />";
        }
        #endregion
    }
    protected string ValidTempFilePath(string PathInfo)
    {
       string WebSitePath = Request.ServerVariables["APPL_PHYSICAL_PATH"];
       PathInfo=PathInfo.Substring(WebSitePath.Length, PathInfo.Length - WebSitePath.Length);
       PathInfo = PathInfo.Replace('\\', '/');
       return PathInfo;
    }
}
